package com.vince.leetcode.medium;

import lombok.NonNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 两数相加
 *
 */
public class _2_AddTwoNumbers {

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    /**
     * 地址：https://leetcode-cn.com/problems/add-two-numbers/
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(@NonNull ListNode l1, @NonNull ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0; // 进位
        while (l1 != null || l2 != null) {
            int val1 = l1 != null ? l1.val : 0;
            int val2 = l2 != null ? l2.val : 0;
            int sum = val1 + val2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail = tail.next = new ListNode(sum % 10);
            }
            carry = sum / 10;
            l1 = l1 != null ? l1.next : null;
            l2 = l2 != null ? l2.next : null;
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }

    private static void printList(ListNode ret) {
        List<Integer> collect = new ArrayList<>();
        while (ret != null) {
            collect.add(ret.val);
            ret = ret.next;
        }
        System.out.println(collect);
    }

    public static void main(String[] args) {
        _2_AddTwoNumbers solution = new _2_AddTwoNumbers();
        printList(solution.addTwoNumbers(
                new ListNode(2, new ListNode(4, new ListNode(3))),
                new ListNode(5, new ListNode(6, new ListNode(4)))));
        printList(solution.addTwoNumbers(
                new ListNode(),
                new ListNode()));
        printList(solution.addTwoNumbers(
                new ListNode(9, new ListNode(9, new ListNode(9,
                        new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))),
                new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))));
    }
}
